package com.ziyun.erp.modules.production.operate;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.service.model.quote.constant.AttributeValueType;
import com.service.order.constant.OrderResult;
import com.service.order.model.address.AddressResultDto;
import com.service.order.model.erp.AllotOrderResultDto;
import com.service.order.model.erp.AllotProductParamDto;
import com.service.order.model.erp.ErpAllotFactoryOrderParamDto;
import com.service.order.model.erp.OldItemNew;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.goods.GoodsTypeEnum;
import com.ziyun.erp.common.e.order.*;
import com.ziyun.erp.common.e.production.OrderProductionStatusEnum;
import com.ziyun.erp.common.e.production.ProducerTypeEnum;
import com.ziyun.erp.common.e.production.ServerCraftEnum;
import com.ziyun.erp.common.e.quoteAttribute.QuoteAttributeValueEnum;
import com.ziyun.erp.common.utils.EnumUtil;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.order.dto.*;
import com.ziyun.erp.modules.order.entity.*;
import com.ziyun.erp.modules.order.service.*;
import com.ziyun.erp.modules.order.vo.UserAccessoryVo;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.erp.modules.production.operate.entity.AllotStateEntity;
import com.ziyun.erp.modules.production.operate.entity.AuditStateEntity;
import com.ziyun.erp.modules.production.operate.entity.LogisticsStateEntity;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import com.ziyun.erp.modules.production.service.ErpOrderProductionService;
import com.ziyun.erp.modules.store.storeGoodsProduct.entity.StoreGoodsProductEntity;
import com.ziyun.erp.modules.store.storeGoodsProduct.service.StoreGoodsProductService;
import com.ziyun.erp.modules.store.storeProductPrice.service.StoreProductPriceService;
import com.ziyun.erp.modules.store.storeProductPrice.vo.StoreProductPriceVo;
import com.ziyun.erp.modules.supp.entity.SellerInfoEntity;
import com.ziyun.erp.modules.supp.service.SellerInfoService;
import com.ziyun.erp.modules.suppOffline.entity.ErpSupplierOfflineEntity;
import com.ziyun.erp.modules.suppOffline.service.ErpSupplierOfflineService;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import com.service.common.constant.GoodsSplitType;
import com.service.common.constant.SplitProcessType;

/**
 * @author guizhao
 * @Title: 待分配状态
 * @ProjectName ziyun-service-erp
 * @date 2018-09-08 15:30
 */
@Slf4j
public class WaitAllotState implements ErpOrderState {

    private OrderInfoService orderInfoService = SpringContextUtils.getBean("orderInfoService",OrderInfoService.class);
    private ErpOrderService erpOrderService = SpringContextUtils.getBean("erpOrderService", ErpOrderService.class);
    private ErpOrderProductionService erpOrderProductionService = SpringContextUtils.getBean("erpOrderProductionService", ErpOrderProductionService.class);
    private ErpOrderItemService erpOrderItemService = SpringContextUtils.getBean("erpOrderItemService", ErpOrderItemService.class);
    private OrderItemService orderItemService = SpringContextUtils.getBean("orderItemService", OrderItemService.class);
    private SellerInfoService sellerInfoService = SpringContextUtils.getBean("sellerInfoService", SellerInfoService.class);
    private ErpOrderAllotRelevanceService relevanceService = SpringContextUtils.getBean("erpOrderAllotRelevanceService", ErpOrderAllotRelevanceService.class);
    private ErpSupplierOfflineService erpSupplierOfflineService = SpringContextUtils.getBean("erpSupplierOfflineService", ErpSupplierOfflineService.class);
    private StoreGoodsProductService storeGoodsProductService = SpringContextUtils.getBean("storeGoodsProductService", StoreGoodsProductService.class);
    private StoreProductPriceService storeProductPriceService = SpringContextUtils.getBean("storeProductPriceService", StoreProductPriceService.class);
    private UserAccessoryService userAccessoryService = SpringContextUtils.getBean("userAccessoryService", UserAccessoryService.class);
    private ErpOrderLogService erpOrderLogService = SpringContextUtils.getBean("erpOrderLogService", ErpOrderLogService.class);

    @Override
    public R audit(AuditStateEntity auditStateEntity) {
        return R.error("不支持操作！");
    }

    @Override
    public R allot(AllotStateEntity allotStateEntity) {
        log.info("=================allot start==================");
        log.info("=================allot params：" + allotStateEntity.toString());
        Integer csId = allotStateEntity.getCsId();
        Integer pmcId = allotStateEntity.getPmcId();
        String allotType = allotStateEntity.getAllotType();
        Integer producer = allotStateEntity.getProducer();
        String orderNo = allotStateEntity.getOrderNo();
        Integer erpItemId = allotStateEntity.getErpItemId();
        BigDecimal cost = allotStateEntity.getCost();
        BigDecimal price = allotStateEntity.getPrice();
        Integer sellerType = allotStateEntity.getSellerType();
        String csRemark = allotStateEntity.getCsRemark();
        ErpOrderEntity erpOrderEntity  = erpOrderService.selectById(orderNo);
        int productionStatus = erpOrderEntity.getProductionStatus().intValue();
        switch (allotType){
            case "order" : {
                // ======================================订单分配===================================================
                log.info("=================order allot start==================");
                if (productionStatus != ProductionStatusEnum.UN_ALLOT.toInt()){
                    return R.error("订单状态异常！");
                }
                int count = erpOrderProductionService.selectCount(new EntityWrapper<>(new ErpOrderProductionEntity())
                        .eq("order_no", orderNo)
                        .eq("del", DeleteEnum.NOT_DELETE.toInt())
                        .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt())
                );
                if (count > 0){
                    return R.error("订单已存在分配信息！");
                }
                Boolean isStandard = allotStateEntity.getIsStandard();
                List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderNo));
                if (isStandard){ // 标品
                    saveOrderAllotStandard(orderNo, orderItemEntityList, cost, producer, csRemark);
                }else { // 报价商品
                    OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = requestOrderAllotQuoteApi(orderNo, orderItemEntityList, producer, csRemark);
                    int code = allotOrderResultDtoOrderResult.getCode();
                    if (code != 1){
                        if (code == 999){
                            return R.error("派单服务异常，请联系后台管理员");
                        }
                        return R.error(allotOrderResultDtoOrderResult.getMessage());
                    }
                    AllotOrderResultDto allotOrderResultDto = allotOrderResultDtoOrderResult.getData();
                    String parentOrderId = allotOrderResultDto.getParentOrderId();
                    saveOrderAllotQuote(orderNo, parentOrderId, cost, producer, csRemark);
                }
                orderAllotStatusUpdate(orderNo, csId, pmcId);

                erpOrderLogService.insertOrderLog(orderNo, "分配中心-订单分配");

                log.info("=================order allot end==================");
            }break;
            case "goods" : {
                // ======================================商品分配===================================================
                log.info("=================goods allot start==================");
                if (productionStatus != ProductionStatusEnum.UN_ALLOT.toInt() && productionStatus != ProductionStatusEnum.IN_PRODUCTION.toInt()){
                    return R.error("订单状态异常！");
                }
                ErpOrderItemEntity erpOrderItem = erpOrderItemService.selectById(erpItemId);
                int status = erpOrderItem.getStatus().intValue();
                if (status != OrderItemStatusEnum.UN_ALLOTED.toInt()){
                    return R.error("商品状态异常！");
                }
                int count = erpOrderProductionService.selectCount(new EntityWrapper<>(new ErpOrderProductionEntity())
                        .where("order_no = {0}", orderNo)
                        .where("erp_item_id = {0}", erpItemId)
                        .where("del = {0}",  DeleteEnum.NOT_DELETE.toInt())
                        .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt())
                );
                if (count > 0){
                    return R.error("商品已存在分配信息！");
                }
                // 是否分配第三方
                boolean allotThird = false;
                // 阳逻发货
                if (producer.intValue() == ErpOrderStateContext.YANGLUO_SUPP_ID){
                    saveItemAllotYangluo(orderNo, erpOrderItem, cost, producer);
                    erpOrderLogService.insertOrderItemLog(orderNo, Long.valueOf(erpOrderItem.getOriginalItemId()),"分配中心-阳逻发货");
                }else {
                    allotThird = true;
                    String addcartBuyType = erpOrderItem.getAddcartBuyType();
                    boolean quoteType = StringUtils.equals(addcartBuyType, "fast") || StringUtils.equals(addcartBuyType, "print");
                    if (!quoteType && sellerType.intValue() == 1){ // 标品商品分配至自营门店
                        saveItemAllotStandard(orderNo, erpOrderItem, cost, price, producer, csRemark);
                    }else { // 标品分配至第三方，报价商品分配至自营门店、第三方
                        Boolean self = allotStateEntity.getSelf();
                        Integer itemId = erpOrderItem.getOriginalItemId();
                        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = requestItemAllotQuoteApi(orderNo, itemId, self, producer, quoteType, csRemark);
                        int code = allotOrderResultDtoOrderResult.getCode();
                        if (code != 1){
                            if (code == 999){
                                return R.error("派单服务异常，请联系后台管理员");
                            }
                            return R.error(allotOrderResultDtoOrderResult.getMessage());
                        }
                        AllotOrderResultDto allotOrderResultDto = allotOrderResultDtoOrderResult.getData();
                        List<OldItemNew> itemList = allotOrderResultDto.getItemList();
                        OldItemNew oldItemNew = itemList.get(0);
                        saveItemAllotQuote(orderNo, erpOrderItem, cost, producer, oldItemNew, csRemark);
                    }
                    erpOrderLogService.insertOrderItemLog(orderNo, Long.valueOf(erpOrderItem.getOriginalItemId()),"分配中心-商品分配");
                }
                itemAllotStatusUpdate(orderNo, erpItemId, csId, pmcId, productionStatus, allotThird);
                log.info("=================goods allot end==================");
            }break;
            case "procedure" : {
                // ======================================工序分配===================================================
                log.info("=================craft allot start==================");
                if (productionStatus != ProductionStatusEnum.UN_ALLOT.toInt() && productionStatus != ProductionStatusEnum.IN_PRODUCTION.toInt()){
                    return R.error("订单状态异常！");
                }
                ErpOrderItemEntity erpOrderItem = erpOrderItemService.selectById(erpItemId);
                int status = erpOrderItem.getStatus().intValue();
                if (status != OrderItemStatusEnum.UN_ALLOTED.toInt() && status != OrderItemStatusEnum.IN_PRODUCTION.toInt()){
                    return R.error("商品状态异常！");
                }
                // 工艺分配
                List<OrderCraftQuoteDto> orderCraftQuoteList = allotStateEntity.getOrderCraftQuoteList();
                if (orderCraftQuoteList != null && orderCraftQuoteList.size() > 0){
                    OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = requestCraftAllotQuoteApi(orderNo, orderCraftQuoteList);
                    int code = allotOrderResultDtoOrderResult.getCode();
                    if (code != 1){
                        if (code == 999){
                            return R.error("派单服务异常，请联系后台管理员");
                        }
                        return R.error(allotOrderResultDtoOrderResult.getMessage());
                    }
                    AllotOrderResultDto allotOrderResultDto = allotOrderResultDtoOrderResult.getData();
                    List<OldItemNew> itemList = allotOrderResultDto.getItemList();
                    saveCraftAllotQuote(orderNo, erpOrderItem, orderCraftQuoteList, itemList);
                }
                // 服务工序
                List<OrderCraftServerDto> orderCraftServerList = allotStateEntity.getOrderCraftServerList();
                if (orderCraftServerList != null && orderCraftServerList.size() > 0){
                    saveServerCraftAllotQuote(orderNo, erpOrderItem, orderCraftServerList);
                }

                erpOrderLogService.insertOrderItemLog(orderNo, Long.valueOf(erpOrderItem.getOriginalItemId()),"分配中心-工序分配");

                craftAllotStatusUpdate(orderNo, erpItemId, status, csId, pmcId, productionStatus);
                log.info("=================craft allot end==================");
            }break;
            default: {return R.error("无效操作");}
        }
        log.info("=================allot end====================");
        return R.ok();
    }

    @Override
    public R receive(Integer productionId) {
        return R.error("不支持操作！");
    }

    @Override
    public R addLogistics(LogisticsStateEntity logisticsStateEntity, String userId, String createName) {
        return R.error("不支持操作！");
    }

    @Override
    public R allotPriceFinish(Integer productionId) {
        return R.error("不支持操作！");
    }

    @Override
    public R cancleAllot(Integer productionId) {
        return R.error("不支持操作！");
    }

    /*
    * ==================================================订单分配=========================================================
    * */

    /**
     * 订单分配：标品（自己生成分配订单信息，保存生产单信息）
     */
    public void saveOrderAllotStandard(String orderNo, List<OrderItemEntity> orderItemEntityList, BigDecimal cost, int producer, String csRemark){
        log.info("=================order allot standard start==================");
        String orderId = orderInfoService.getOrderId();
        // 商品信息
        for (OrderItemEntity orderItemEntity : orderItemEntityList){
            Integer itemId = orderItemEntity.getItemId();
            Integer productId = orderItemEntity.getProductId();
            // 标品，查询门店配置价格信息(价格以紫云网配置价格为准)
            List<StoreGoodsProductEntity> storeGoodsProductList = storeGoodsProductService.selectList(new EntityWrapper<>(new StoreGoodsProductEntity())
                    .eq("orig_product_id", productId)
                    .eq("disabled", DeleteEnum.NOT_DELETE.toInt())
            );
            List<Integer> productIds = storeGoodsProductList.stream().map(StoreGoodsProductEntity::getProductId).collect(Collectors.toList());
            Map<String, Object> params = new HashMap<>();
            params.put("productIds", productIds);
            List<StoreProductPriceVo> storeProductPriceVos = storeProductPriceService.selectStoreProductPriceVoList(params);
            // 查询 紫云工厂(分配) 账号是否配价格，若配价格，以此价格为准；若未配价格，提示返回
            List<StoreProductPriceVo> storeProductPriceVoList = storeProductPriceVos.stream()
                    .filter((item) -> item.getSellerId().intValue() == ErpOrderStateContext.ZIYUN_FACTORY_ID.intValue())
                    .collect(Collectors.toList());
            StoreProductPriceVo storeProductPrice = storeProductPriceVoList.get(0);
            BigDecimal price = storeProductPrice.getPrice();
            BigDecimal nums = orderItemEntity.getNums();

            // 查询是否有阶梯价
            String stepPrice = storeProductPrice.getStepPrice();
            if (StringUtils.isNotBlank(stepPrice)){
                BigDecimal sprice = erpOrderService.calculateStepPrice(stepPrice, nums);
                if (sprice != null){
                    price = sprice;
                }
            }
            BigDecimal amount = price.multiply(nums);

            // 查询是否广告物料商品
            String goodsType = orderItemEntity.getGoodsType();
            if (goodsType.equals(GoodsTypeEnum.MATERIAL.toCode())) {
                Long goodsId = orderItemEntity.getGoodsId();
                String addon = orderItemEntity.getAddon();
                BigDecimal aprice = erpOrderService.calculateMaterialGoodsPrice(goodsId, addon, amount);
                if (aprice != null){
                    amount = aprice;
                }
            }

            orderItemEntity.setPrice(price);
            orderItemEntity.setAmount(amount);
            orderItemEntity.setSharePrice(BigDecimal.ZERO);
            orderItemEntity.setOrderId(Long.valueOf(orderId));
            orderItemService.insert(orderItemEntity);

            // 查询待分配订单是否上传源文件信息
            List<UserAccessoryVo> userAccessoryVos = userAccessoryService.queryListByItemId(itemId.toString());
            if (userAccessoryVos != null && userAccessoryVos.size() > 0){
                userAccessoryService.saveAllotOrderFiles(userAccessoryVos, orderId, orderItemEntity.getItemId(), ErpOrderStateContext.ZIYUN_USER_ID);
            }
        }

        // 订单信息
        OrderInfoEntity orderInfo = orderInfoService.selectById(orderNo);
        OrderInfoEntity merchantsOrder = new OrderInfoEntity();
        merchantsOrder.setOrderId(orderId);
        merchantsOrder.setUserId(ErpOrderStateContext.ZIYUN_USER_ID);
        merchantsOrder.setParentOrderId(Long.valueOf(orderId));
        merchantsOrder.setSupplierId(producer);
        merchantsOrder.setTotalAmount(cost);
        merchantsOrder.setPayableAmount(cost);
        merchantsOrder.setCreatetime(new Date());
        merchantsOrder.setPromotionType(orderInfo.getPromotionType());
        merchantsOrder.setPickUp(orderInfo.getPickUp());
        // 分配到自营门店，收货人信息填写紫云网订单收货人信息
        merchantsOrder.setShipAreaId(orderInfo.getShipAreaId());
        merchantsOrder.setShipArea(orderInfo.getShipArea());
        merchantsOrder.setShipName(orderInfo.getShipName());
        merchantsOrder.setShipAddr(orderInfo.getShipAddr());
        merchantsOrder.setShipZip(orderInfo.getShipZip());
        merchantsOrder.setShipTel(orderInfo.getShipTel());
        merchantsOrder.setShipEmail(orderInfo.getShipEmail());
        merchantsOrder.setShipTime(orderInfo.getShipTime());
        merchantsOrder.setShipMobile(orderInfo.getShipMobile());
        String memo = "紫云网分配订单：订单号：" + orderNo;
        if (StringUtils.isNotBlank(csRemark)){
            memo += "；留言：" + csRemark;
        }
        merchantsOrder.setMemo(memo);
        merchantsOrder.setSource(SourceEnum.PC.toCode());
        orderInfoService.insert(merchantsOrder);

        // 保存生产单信息
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderNo);
        erpOrderProduction.setAllotType("order");
        if (cost != null){
            erpOrderProduction.setCostStatus(true);
            erpOrderProduction.setCost(cost);
        }
        erpOrderProduction.setProducer(producer);
        SellerInfoEntity sellerInfo = sellerInfoService.selectById(producer);
        erpOrderProduction.setProducerName(sellerInfo.getSellerName());
        erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        erpOrderProduction.setOnlineCash(1);
        erpOrderProduction.setProducerType(ProducerTypeEnum.SELF_MERCHANT.toInt());
        erpOrderProduction.setProductionOrder(orderId);
        erpOrderProduction.setCsRemark(csRemark);
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.UN_PRODUCE.toInt());
        erpOrderProductionService.insert(erpOrderProduction);

        // 保存分配关系
        ErpOrderAllotRelevanceEntity relevanceEntity = new ErpOrderAllotRelevanceEntity();
        relevanceEntity.setOriginalOrderNo(orderNo);
        relevanceEntity.setOrderAllotNo(orderId);
        relevanceEntity.setProductionId(erpOrderProduction.getProductionId());
        relevanceEntity.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        relevanceService.insert(relevanceEntity);
        log.info("=================order allot standard end==================");
    }

    /**
     * 订单分配：报价商品（请求API生成订单信息）
     */
    public OrderResult<AllotOrderResultDto> requestOrderAllotQuoteApi(String orderNo, List<OrderItemEntity> orderItemEntityList, int producer, String csRemark){
        log.info("=================order allot quote api start==================");
        // 地址信息,分配到自营门店，收货人信息填写紫云网订单收货人信息
        OrderInfoEntity orderInfoEntity = orderInfoService.selectById(orderNo);
        AddressResultDto addressResultDto = new AddressResultDto();
//        addressResultDto.setAddressId(orderInfoEntity.getUserId());
        addressResultDto.setName(orderInfoEntity.getShipName());
        addressResultDto.setArea(orderInfoEntity.getShipArea());
        addressResultDto.setAreaId(orderInfoEntity.getShipAreaId());
        addressResultDto.setAddr(orderInfoEntity.getShipAddr());
        addressResultDto.setMobile(orderInfoEntity.getShipMobile());
        addressResultDto.setPickUp(orderInfoEntity.getPickUp());
        // 商品分配信息
        List<AllotProductParamDto> AllotProductParamDtoList = new ArrayList<>();
        for (OrderItemEntity orderItemEntity : orderItemEntityList){
            AllotProductParamDto allotProductParamDto = new AllotProductParamDto();
            allotProductParamDto.setOrderItemId(orderItemEntity.getItemId());
            allotProductParamDto.setSellerId(Long.valueOf(producer));
            allotProductParamDto.setReferToSellerId(ErpOrderStateContext.ZIYUN_FACTORY_ID);
            AllotProductParamDtoList.add(allotProductParamDto);
        }
        // 备注
        String memo = "紫云网分配订单：订单号：" + orderNo;
        if (StringUtils.isNotBlank(csRemark)){
            memo += "；留言：" + csRemark;
        }
        // 分配信息
        ErpAllotFactoryOrderParamDto erpAllotFactoryOrderParamDto = ErpAllotFactoryOrderParamDto.builder()
                .userId(Long.valueOf(ErpOrderStateContext.ZIYUN_USER_ID))
                .sellerId(Long.valueOf(ErpOrderStateContext.ZIYUN_SELLER_ID))
                .self(true)
                .goodsSplitType(GoodsSplitType.quoteGoods)
                .allotOrderId(orderNo)
                .address(addressResultDto)
                .quoteParam(AllotProductParamDtoList)
                .memo(memo)
                .build();
        log.info("=================order allot quote api param:" + JsonUtils.object2String(erpAllotFactoryOrderParamDto));
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = erpOrderService.orderAllotApi(erpAllotFactoryOrderParamDto);
        log.info("=================order allot quote api result:" + JsonUtils.object2String(allotOrderResultDtoOrderResult));
        log.info("=================order allot quote api end==================");
        return allotOrderResultDtoOrderResult;
    }

    /**
     * 订单分配：报价商品分配后保存生产单信息
     */
    public void saveOrderAllotQuote(String orderNo, String parentOrderId, BigDecimal cost, int producer, String csRemark) {
        // 生成生产单
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderNo);
        erpOrderProduction.setAllotType("order");
        erpOrderProduction.setOnlineCash(1);
        erpOrderProduction.setProducer(producer);
        SellerInfoEntity sellerInfo= sellerInfoService.selectById(producer);
        erpOrderProduction.setProducerName(sellerInfo.getSellerName());
        erpOrderProduction.setProducerType(ProducerTypeEnum.SELF_MERCHANT.toInt());
        if (cost != null){
            erpOrderProduction.setCostStatus(true);
            erpOrderProduction.setCost(cost);
        }
        erpOrderProduction.setCsRemark(csRemark);
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.UN_PRODUCE.toInt());
        erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        erpOrderProduction.setProductionOrder(parentOrderId);
        erpOrderProductionService.insert(erpOrderProduction);
        // 保存分配关系
        ErpOrderAllotRelevanceEntity relevanceEntity = new ErpOrderAllotRelevanceEntity();
        relevanceEntity.setOriginalOrderNo(orderNo);
        relevanceEntity.setOrderAllotNo(parentOrderId);
        relevanceEntity.setProductionId(erpOrderProduction.getProductionId());
        relevanceEntity.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        relevanceService.insert(relevanceEntity);
    }

    /**
     * 订单分配：订单、商品状态改变
     */
    public void orderAllotStatusUpdate(String orderNo, int csId, int pmcId){
        // 订单状态 待分配 =》 生产中
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("csId", csId);
        updateMap.put("pmcId", pmcId);
        updateMap.put("allotName", UserUtils.getCurentUser().getUserId());
        updateMap.put("allotTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        updateMap.put("productionStatus", ProductionStatusEnum.IN_PRODUCTION.toInt());
        updateMap.put("allotThirdStatus", 1);
        erpOrderService.updateByMap(updateMap, orderNo);
        // 商品状态 待分配=》生产中
        List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemService.selectList(new EntityWrapper<>(new ErpOrderItemEntity())
                .eq("order_no", orderNo)
                .eq("item_del", DeleteEnum.NOT_DELETE.toInt())
        );
        List<Integer> ids = erpOrderItemList.stream().map(ErpOrderItemEntity::getEoItemId).collect(Collectors.toList());
        updateMap.clear();
        updateMap.put("status", OrderItemStatusEnum.IN_PRODUCTION.toInt());
        erpOrderItemService.updateBatchByMap(updateMap, ids);
    }


    /*
     * ==================================================商品分配=========================================================
     * */

    /**
     * 商品分配：阳逻发货，只生成生产单信息
     */
    public void saveItemAllotYangluo(String orderNo, ErpOrderItemEntity erpOrderItem, BigDecimal cost, int producer){
        // 生成生产单
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderNo);
        erpOrderProduction.setAllotType("goods");
        erpOrderProduction.setErpItemId(erpOrderItem.getEoItemId().toString());
        erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
        erpOrderProduction.setAddon(erpOrderItem.getAddon());
        erpOrderProduction.setUnit(erpOrderItem.getUnit());
        erpOrderProduction.setNums(erpOrderItem.getNums());
        if (cost != null){
            erpOrderProduction.setCostStatus(true);
            erpOrderProduction.setCost(cost);
        }
        erpOrderProduction.setProducer(producer);
        ErpSupplierOfflineEntity erpSupplierOffline = erpSupplierOfflineService.selectById(producer);
        erpOrderProduction.setProducerName(erpSupplierOffline.getSupplierName());
        erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        erpOrderProduction.setOnlineCash(0);
        erpOrderProduction.setProducerType(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt());
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.PRODUCING.toInt());
        erpOrderProductionService.insert(erpOrderProduction);
    }

    /**
     * 商品分配：标品 （自己生成分配订单信息，保存生产单信息）
     */
    public void saveItemAllotStandard(String orderNo, ErpOrderItemEntity erpOrderItem, BigDecimal cost, BigDecimal price, int producer, String csRemark){
        // 标品，且是分配至自营门店，创建订单，订单与原分配订单信息一致
        String orderId = orderInfoService.getOrderId();
        // 商品信息
        Integer originalItemId = erpOrderItem.getOriginalItemId();
        OrderItemEntity orderItem = orderItemService.selectById(originalItemId);
        orderItem.setOrderId(Long.valueOf(orderId));
        orderItem.setAmount(cost);
        orderItem.setPrice(price);
        orderItem.setSharePrice(BigDecimal.ZERO);
        orderItemService.insert(orderItem);

        // 查询待分配订单是否上传源文件信息
        List<UserAccessoryVo> userAccessoryVos = userAccessoryService.queryListByItemId(originalItemId.toString());
        if (userAccessoryVos != null && userAccessoryVos.size() > 0){
            userAccessoryService.saveAllotOrderFiles(userAccessoryVos, orderId, orderItem.getItemId(), ErpOrderStateContext.ZIYUN_USER_ID);
        }

        // 订单信息
        OrderInfoEntity orderInfo = orderInfoService.selectById(orderNo);
        OrderInfoEntity merchantsOrder = new OrderInfoEntity();
        merchantsOrder.setOrderId(orderId);
        merchantsOrder.setUserId(ErpOrderStateContext.ZIYUN_USER_ID);
        merchantsOrder.setParentOrderId(Long.valueOf(orderId));
        merchantsOrder.setSupplierId(producer);
        merchantsOrder.setTotalAmount(cost);
        merchantsOrder.setPayableAmount(cost);
        merchantsOrder.setCreatetime(new Date());
        merchantsOrder.setPromotionType(orderInfo.getPromotionType());
        merchantsOrder.setPickUp(orderInfo.getPickUp());
        merchantsOrder.setShipAreaId(orderInfo.getShipAreaId());
        merchantsOrder.setShipArea(orderInfo.getShipArea());
        merchantsOrder.setShipName(orderInfo.getShipName());
        merchantsOrder.setShipAddr(orderInfo.getShipAddr());
        merchantsOrder.setShipZip(orderInfo.getShipZip());
        merchantsOrder.setShipTel(orderInfo.getShipTel());
        merchantsOrder.setShipEmail(orderInfo.getShipEmail());
        merchantsOrder.setShipTime(orderInfo.getShipTime());
        merchantsOrder.setShipMobile(orderInfo.getShipMobile());
        String memo = "紫云网分配订单：订单号：" + orderNo;
        if (StringUtils.isNotBlank(csRemark)){
            memo += "；留言：" + csRemark;
        }
        merchantsOrder.setMemo(memo);
        merchantsOrder.setSource(SourceEnum.PC.toCode());
        orderInfoService.insert(merchantsOrder);

        // 保存生产单信息
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderNo);
        erpOrderProduction.setAllotType("goods");
        erpOrderProduction.setErpItemId(erpOrderItem.getEoItemId().toString());
        erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
        erpOrderProduction.setAddon(erpOrderItem.getAddon());
        erpOrderProduction.setUnit(erpOrderItem.getUnit());
        erpOrderProduction.setNums(erpOrderItem.getNums());
        if (cost != null){
            erpOrderProduction.setCostStatus(true);
            erpOrderProduction.setCost(cost);
        }
        erpOrderProduction.setProducer(producer);
        SellerInfoEntity sellerInfo = sellerInfoService.selectById(producer);
        erpOrderProduction.setProducerName(sellerInfo.getSellerName());
        erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        erpOrderProduction.setOnlineCash(1);
        erpOrderProduction.setCsRemark(csRemark);
        erpOrderProduction.setProducerType(ProducerTypeEnum.SELF_MERCHANT.toInt());
        erpOrderProduction.setProductionOrder(orderId);
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.UN_PRODUCE.toInt());
        erpOrderProductionService.insert(erpOrderProduction);

        // 保存分配关系
        ErpOrderAllotRelevanceEntity relevanceEntity = new ErpOrderAllotRelevanceEntity();
        relevanceEntity.setOriginalOrderNo(orderNo);
        relevanceEntity.setOrderAllotNo(orderId);
        relevanceEntity.setProductionId(erpOrderProduction.getProductionId());
        relevanceEntity.setOriginalItemId(originalItemId);
        relevanceEntity.setItemAllotId(orderItem.getItemId());
        relevanceEntity.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        relevanceService.insert(relevanceEntity);
    }

    /**
     * 商品分配：报价商品（请求API生成订单信息）
     */
    public OrderResult<AllotOrderResultDto> requestItemAllotQuoteApi(String orderNo, int itemId, boolean self, int producer, boolean quoteType, String csRemark){
        log.info("=================goods allot quote api start==================");
        // 商品分配信息
        List<AllotProductParamDto> AllotProductParamDtoList = new ArrayList<>();
        AllotProductParamDto allotProductParamDto = new AllotProductParamDto();
        // 地址信息，分配到自营门店，收货人信息填写紫云网订单收货人信息
        AddressResultDto addressResultDto = new AddressResultDto();
        String memo = null;
        if (self){
            memo = "紫云网分配订单：订单号：" + orderNo;
            if (StringUtils.isNotBlank(csRemark)){
                memo += "；留言：" + csRemark;
            }
            // 小B参考工厂ID，若是自营，统一填写紫云网 factory_id
            allotProductParamDto.setReferToSellerId(ErpOrderStateContext.ZIYUN_FACTORY_ID);

            OrderInfoEntity orderInfoEntity = orderInfoService.selectById(orderNo);
//            addressResultDto.setAddressId(orderInfoEntity.getUserId());
            addressResultDto.setName(orderInfoEntity.getShipName());
            addressResultDto.setArea(orderInfoEntity.getShipArea());
            addressResultDto.setAreaId(orderInfoEntity.getShipAreaId());
            addressResultDto.setAddr(orderInfoEntity.getShipAddr());
            addressResultDto.setMobile(orderInfoEntity.getShipMobile());
            addressResultDto.setPickUp(orderInfoEntity.getPickUp());
        }else {
            memo = csRemark;
            allotProductParamDto.setReferToSellerId(Long.valueOf(producer));

            SellerInfoEntity sellerInfoEntity = sellerInfoService.selectById(ErpOrderStateContext.ZIYUN_SELLER_ID);
//            addressResultDto.setAddressId(sellerInfoEntity.getSellerId());
            addressResultDto.setName(sellerInfoEntity.getSellerName());
            addressResultDto.setArea(sellerInfoEntity.getArea());
            addressResultDto.setAreaId(Integer.valueOf(sellerInfoEntity.getAreaId()));
            addressResultDto.setAddr(sellerInfoEntity.getAddr());
            addressResultDto.setMobile(sellerInfoEntity.getSellerMobile());
            addressResultDto.setPickUp(true);
        }
        allotProductParamDto.setOrderItemId(itemId);
        allotProductParamDto.setSellerId(Long.valueOf(producer));
        AllotProductParamDtoList.add(allotProductParamDto);

        // 订单信息
        ErpAllotFactoryOrderParamDto erpAllotFactoryOrderParamDto = ErpAllotFactoryOrderParamDto.builder()
                .allotOrderId(orderNo)
                .userId(Long.valueOf(ErpOrderStateContext.ZIYUN_USER_ID))
                .sellerId(Long.valueOf(ErpOrderStateContext.ZIYUN_SELLER_ID))
                .self(self)
                .goodsSplitType(quoteType == true ? GoodsSplitType.quoteGoods : GoodsSplitType.standardGoods)
                .address(addressResultDto)
                .quoteParam(AllotProductParamDtoList)
                .memo(memo)
                .build();

        log.info("=================order allot quote api param:" + JsonUtils.object2String(erpAllotFactoryOrderParamDto));
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = erpOrderService.orderAllotApi(erpAllotFactoryOrderParamDto);
        log.info("=================order allot quote api result:" + JsonUtils.object2String(allotOrderResultDtoOrderResult));
        log.info("=================goods allot quote api end==================");
        return allotOrderResultDtoOrderResult;
    }

    /**
     * 商品分配：报价商品分配后保存生产单信息
     */
    public void saveItemAllotQuote(String orderNo, ErpOrderItemEntity erpOrderItem, BigDecimal cost, int producer, OldItemNew oldItemNew, String csRemark) {
        int oldItemId = oldItemNew.getOldItemId();
        String newOrderId = oldItemNew.getNewOrderId();
        int newItemId = oldItemNew.getNewItemId();

        // 查询待分配订单是否上传源文件信息
        List<UserAccessoryVo> userAccessoryVos = userAccessoryService.queryListByItemId(String.valueOf(oldItemId));
        if (userAccessoryVos != null && userAccessoryVos.size() > 0){
            userAccessoryService.saveAllotOrderFiles(userAccessoryVos, newOrderId, newItemId, ErpOrderStateContext.ZIYUN_USER_ID);
        }

        // 保存生产单信息
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderNo);
        erpOrderProduction.setAllotType("goods");
        erpOrderProduction.setErpItemId(erpOrderItem.getEoItemId().toString());
        erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
        erpOrderProduction.setAddon(erpOrderItem.getAddon());
        erpOrderProduction.setUnit(erpOrderItem.getUnit());
        erpOrderProduction.setNums(erpOrderItem.getNums());
        if (cost != null){
            erpOrderProduction.setCostStatus(true);
            erpOrderProduction.setCost(cost);
        }
        erpOrderProduction.setProducer(producer);
        SellerInfoEntity sellerInfo = sellerInfoService.selectById(producer);
        erpOrderProduction.setProducerName(sellerInfo.getSellerName());
        erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        erpOrderProduction.setOnlineCash(1);
        String sellerType = sellerInfo.getSellerType();
        if ("0".equals(sellerType)){
            Integer self = sellerInfo.getSelf();
            if (self.intValue() == 1){
                erpOrderProduction.setProducerType(ProducerTypeEnum.SELF_MERCHANT.toInt());
            }else {
                erpOrderProduction.setProducerType(ProducerTypeEnum.NON_SELF_MERCHANT.toInt());
            }
        }else {
            erpOrderProduction.setProducerType(ProducerTypeEnum.QUOTE_FACTORY.toInt());
        }
        erpOrderProduction.setCsRemark(csRemark);
        erpOrderProduction.setProductionOrder(newOrderId);
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.UN_PRODUCE.toInt());
        erpOrderProductionService.insert(erpOrderProduction);
        // 保存分配关系
        ErpOrderAllotRelevanceEntity relevanceEntity = new ErpOrderAllotRelevanceEntity();
        relevanceEntity.setOriginalOrderNo(orderNo);
        relevanceEntity.setOrderAllotNo(newOrderId);
        relevanceEntity.setProductionId(erpOrderProduction.getProductionId());
        relevanceEntity.setOriginalItemId(oldItemId);
        relevanceEntity.setItemAllotId(newItemId);
        relevanceEntity.setCreateName(UserUtils.getCurentUser().getUserId().toString());
        relevanceService.insert(relevanceEntity);
    }

    /**
     * 商品分配：订单、商品状态改变
     */
    public void itemAllotStatusUpdate(String orderNo, int erpItemId, int csId, int pmcId, int productionStatus, boolean allotThird){
        // 订单商品状态 待分配 =》 生产中
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", OrderItemStatusEnum.IN_PRODUCTION.toInt());
        erpOrderItemService.updateByMap(updateMap, erpItemId);

        // 订单状态 待分配 =》 生产中
        if (productionStatus == ProductionStatusEnum.UN_ALLOT.toInt()){
            updateMap.clear();
            updateMap.put("allotName", UserUtils.getCurentUser().getUserId());
            updateMap.put("allotTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            updateMap.put("csId", csId);
            updateMap.put("pmcId", pmcId);
            updateMap.put("productionStatus", ProductionStatusEnum.IN_PRODUCTION.toInt());
            if (allotThird){
                updateMap.put("allotThirdStatus", 1);
            }
            erpOrderService.updateByMap(updateMap, orderNo);
        }
    }

    /*
     * ==================================================工序分配=========================================================
     * */

    /**
     * 工序分配：报价商品（请求API生成订单信息）
     */
    public OrderResult<AllotOrderResultDto> requestCraftAllotQuoteApi(String orderNo, List<OrderCraftQuoteDto> orderCraftQuoteList) {
        log.info("=================craft allot quote api start==================");
        // 地址信息
        SellerInfoEntity sellerInfoEntity = sellerInfoService.selectById(ErpOrderStateContext.ZIYUN_SELLER_ID);
        AddressResultDto addressResultDto = new AddressResultDto();
//        addressResultDto.setAddressId(sellerInfoEntity.getSellerId());
        addressResultDto.setName(sellerInfoEntity.getSellerName());
        addressResultDto.setArea(sellerInfoEntity.getArea());
        addressResultDto.setAreaId(Integer.valueOf(sellerInfoEntity.getAreaId()));
        addressResultDto.setAddr(sellerInfoEntity.getAddr());
        addressResultDto.setMobile(sellerInfoEntity.getSellerMobile());
        addressResultDto.setPickUp(true);
        // 商品分配信息
        List<AllotProductParamDto> AllotProductParamDtoList = new ArrayList<>();
        for (OrderCraftQuoteDto orderCraftQuoteDto : orderCraftQuoteList){
            AllotProductParamDto allotProductParamDto = new AllotProductParamDto();
            allotProductParamDto.setOrderItemId(orderCraftQuoteDto.getOrderItemId());
            allotProductParamDto.setPartId(orderCraftQuoteDto.getPartId());
            allotProductParamDto.setSplitProcessType(SplitProcessType.valueOf(orderCraftQuoteDto.getSplitProcessType()));
            allotProductParamDto.setCraftValueType(AttributeValueType.valueOf(orderCraftQuoteDto.getCraftValueType()));
            allotProductParamDto.setSellerId(Long.valueOf(orderCraftQuoteDto.getSellerId()));
            allotProductParamDto.setProductId(Long.valueOf(orderCraftQuoteDto.getProductId()));
            Boolean self = orderCraftQuoteDto.getSelf();
            if (self){
                allotProductParamDto.setReferToSellerId(ErpOrderStateContext.ZIYUN_FACTORY_ID);
            }else {
                allotProductParamDto.setReferToSellerId(Long.valueOf(orderCraftQuoteDto.getSellerId()));
            }
            AllotProductParamDtoList.add(allotProductParamDto);
        }

        // 分配信息
        // 全部选的自营供应商分配为 true， 其他为 false
        boolean self = false;
        long count = orderCraftQuoteList.stream().filter(item -> !item.getSelf()).count();
        if (count == 0){
            self = true;
        }
        ErpAllotFactoryOrderParamDto erpAllotFactoryOrderParamDto = ErpAllotFactoryOrderParamDto.builder()
                .allotOrderId(orderNo)
                .userId(Long.valueOf(ErpOrderStateContext.ZIYUN_USER_ID))
                .sellerId(Long.valueOf(ErpOrderStateContext.ZIYUN_SELLER_ID))
                .self(self)
                .goodsSplitType(GoodsSplitType.quoteGoodsSplit)
                .address(addressResultDto)
                .quoteParam(AllotProductParamDtoList)
                .build();
        log.info("=================order allot quote api param:" + JsonUtils.object2String(erpAllotFactoryOrderParamDto));
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = erpOrderService.orderAllotApi(erpAllotFactoryOrderParamDto);
        log.info("=================order allot quote api result:" + JsonUtils.object2String(allotOrderResultDtoOrderResult));
        log.info("=================craft allot quote api end==================");
        return allotOrderResultDtoOrderResult;
    }

    /**
     * 工序分配：报价商品分配后保存生产单信息
     */
    public void saveCraftAllotQuote(String orderNo, ErpOrderItemEntity erpOrderItem, List<OrderCraftQuoteDto> orderCraftQuoteList, List<OldItemNew> itemList) {
        for (OldItemNew re : itemList){
            String newOrderId = re.getNewOrderId();
            int oldItemId = re.getOldItemId();
            int newItemId = re.getNewItemId();
            int partId = re.getPartId();
            String craftValueType = re.getCraftValueType().toString();
            String splitProcessType = re.getSplitProcessType().toString();
            List<OrderCraftQuoteDto> collect = orderCraftQuoteList.stream()
                    .filter(item -> item.getPartId().intValue() == partId && item.getCraftValueType().equals(craftValueType) && item.getSplitProcessType().equals(splitProcessType))
                    .collect(Collectors.toList());
            OrderCraftQuoteDto orderCraftQuoteDto = collect.get(0);

            // 查询待分配订单是否上传源文件信息
            List<UserAccessoryVo> userAccessoryVos = userAccessoryService.queryListByItemId(String.valueOf(oldItemId));
            if (userAccessoryVos != null && userAccessoryVos.size() > 0){
                userAccessoryService.saveAllotOrderFiles(userAccessoryVos, newOrderId, newItemId, ErpOrderStateContext.ZIYUN_USER_ID);
            }

            // 生成生产单
            ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
            erpOrderProduction.setOrderNo(orderNo);
            erpOrderProduction.setPartId(partId);
            erpOrderProduction.setPartsName(orderCraftQuoteDto.getPartsName());
            erpOrderProduction.setAttributeTypeValue(craftValueType);
            if (StringUtils.equals(craftValueType, "material")){
                erpOrderProduction.setAttributeName("纸张");
            }else if (StringUtils.equals(craftValueType, "size")){
                erpOrderProduction.setAttributeName("印刷");
            }else {
                erpOrderProduction.setAttributeName(EnumUtil.getEnumByCode(QuoteAttributeValueEnum.class,craftValueType).toDescribe());
            }
            erpOrderProduction.setAllotType("procedure");
            erpOrderProduction.setOnlineCash(1);
            erpOrderProduction.setErpItemId(erpOrderItem.getEoItemId().toString());
            erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
            erpOrderProduction.setAddon(erpOrderItem.getAddon());
            erpOrderProduction.setUnit(erpOrderItem.getUnit());
            erpOrderProduction.setNums(erpOrderItem.getNums());

            Integer sellerId = orderCraftQuoteDto.getSellerId();
            erpOrderProduction.setProducer(sellerId);
            SellerInfoEntity sellerInfo = sellerInfoService.selectById(sellerId);
            erpOrderProduction.setProducerName(sellerInfo.getSellerName());
            String sellerType = sellerInfo.getSellerType();
            if ("0".equals(sellerType)){
                erpOrderProduction.setProducerType(ProducerTypeEnum.NON_SELF_MERCHANT.toInt());
            }else {
                erpOrderProduction.setProducerType(ProducerTypeEnum.QUOTE_FACTORY.toInt());
            }
            BigDecimal totalPrice = orderCraftQuoteDto.getTotalPrice();
            if (totalPrice != null){
                erpOrderProduction.setCostStatus(true);
                erpOrderProduction.setCost(totalPrice);
            }
            erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.UN_PRODUCE.toInt());
            erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
            erpOrderProduction.setProductionOrder(newOrderId);
            erpOrderProduction.setCsRemark(orderCraftQuoteDto.getRemark());
            erpOrderProductionService.insert(erpOrderProduction);

            // 保存分配关系
            ErpOrderAllotRelevanceEntity relevanceEntity = new ErpOrderAllotRelevanceEntity();
            relevanceEntity.setOriginalOrderNo(orderNo);
            relevanceEntity.setOrderAllotNo(newOrderId);
            relevanceEntity.setProductionId(erpOrderProduction.getProductionId());
            relevanceEntity.setOriginalItemId(oldItemId);
            relevanceEntity.setItemAllotId(newItemId);
            relevanceEntity.setCreateName(UserUtils.getCurentUser().getUserId().toString());
            relevanceService.insert(relevanceEntity);
        }
    }

    /**
     * 工序分配：服务工序分配，保存生产单信息
     */
    public void saveServerCraftAllotQuote(String orderNo, ErpOrderItemEntity erpOrderItem, List<OrderCraftServerDto> orderCraftServerList){
        List<ErpOrderProductionEntity> productionList = new ArrayList<>(orderCraftServerList.size());
        for (OrderCraftServerDto orderCraftServerDto : orderCraftServerList){
            ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
            erpOrderProduction.setAttributeTypeValue(orderCraftServerDto.getCraftValueType());
            // 部件ID 不为空，为自做工序，否则为服务工序
            if (orderCraftServerDto.getPartId() != null){
                erpOrderProduction.setAttributeName(EnumUtil.getEnumByCode(QuoteAttributeValueEnum.class, orderCraftServerDto.getCraftValueType()).toDescribe());
            }else {
                erpOrderProduction.setAttributeName(EnumUtil.getEnumByCode(ServerCraftEnum.class, orderCraftServerDto.getCraftValueType()).toDescribe());
            }
            // 是否自做
            if (orderCraftServerDto.getIsOwn()){
                erpOrderProduction.setIsOwn(1);
            }
            erpOrderProduction.setPartId(orderCraftServerDto.getPartId());
            erpOrderProduction.setProducer(orderCraftServerDto.getSupplierId());
            ErpSupplierOfflineEntity erpSupplierOffline = erpSupplierOfflineService.selectById(orderCraftServerDto.getSupplierId());
            erpOrderProduction.setProducerName(erpSupplierOffline.getSupplierName());
            BigDecimal totalPrice = orderCraftServerDto.getTotalPrice();
            if (totalPrice != null){
                erpOrderProduction.setCostStatus(true);
                erpOrderProduction.setCost(totalPrice);
            }
            erpOrderProduction.setCsRemark(orderCraftServerDto.getRemark());
            erpOrderProduction.setOrderNo(orderNo);
            erpOrderProduction.setAllotType("procedure");
            erpOrderProduction.setErpItemId(erpOrderItem.getEoItemId().toString());
            erpOrderProduction.setOrderItemId(erpOrderItem.getOriginalItemId().toString());
            erpOrderProduction.setAddon(erpOrderItem.getAddon());
            erpOrderProduction.setUnit(erpOrderItem.getUnit());
            erpOrderProduction.setNums(erpOrderItem.getNums());
            erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.PRODUCING.toInt());
            erpOrderProduction.setCreateName(UserUtils.getCurentUser().getUserId().toString());
            erpOrderProduction.setProducerType(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt());
            erpOrderProduction.setOnlineCash(0);
            productionList.add(erpOrderProduction);
        }
        erpOrderProductionService.insertBatch(productionList);
    }

    /**
     * 工序分配：订单、商品状态改变
     */
    public void craftAllotStatusUpdate(String orderNo, int erpItemId, int status, int csId, int pmcId, int productionStatus){
        // 订单商品状态 待分配 =》 生产中
        Map<String, Object> updateMap = new HashMap<>();
        if (status == OrderItemStatusEnum.UN_ALLOTED.toInt()){
            updateMap.put("status", OrderItemStatusEnum.IN_PRODUCTION.toInt());
            erpOrderItemService.updateByMap(updateMap, erpItemId);
        }
        // 订单状态 待分配 =》 生产中
        if (productionStatus == ProductionStatusEnum.UN_ALLOT.toInt()){
            updateMap.clear();
            updateMap.put("csId", csId);
            updateMap.put("pmcId", pmcId);
            updateMap.put("allotName", UserUtils.getCurentUser().getUserId());
            updateMap.put("allotTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            updateMap.put("productionStatus", ProductionStatusEnum.IN_PRODUCTION.toInt());
            updateMap.put("allotThirdStatus", 1);
            erpOrderService.updateByMap(updateMap, orderNo);
        }
    }
}
